<template>
  <div class="users-base-wrapper">
    <div class="module-name">
      <div>
        <span style="display: inline-block; border-left: 4px solid #753cca; line-height: 25px; padding-left: 12px;">变量配置({{ queryParams.name }})</span>
      </div>
      <el-button size="mini" type="default" icon="el-icon-arrow-left" @click="handleGoBack">返回上一级</el-button>
    </div>
    <div class="details-layout">
      <el-row style="text-align: left; margin-bottom: 16px;">
        <el-button type="primary" size="mini" @click="handleRefresh">刷新</el-button>
        <el-button type="primary" size="mini" @click="handleAdd" v-if="isOperate" icon="el-icon-plus">新增</el-button>
      </el-row>
      <el-table :data="variableConfigList" stripe style="width: 100%" size="mini" row-key="id"
                :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :tree-props="{ children: 'children' }">
        <el-table-column
          type="index"
          label="序号"
          width="50">
        </el-table-column>
        <template v-for="(column, index) in tableColumns">
          <el-table-column v-if="column.visible" :width="column.width" :key="index" :min-width="column.minWidth" 
                           :label="column.name" :show-overflow-tooltip="true" align="center">
            <template slot-scope="scope">
              <!-- 编辑 -->
              <div v-if="column.key === 'edit'">
                <i class="el-icon-edit table-icon" @click="handleEdit(scope.row)" v-if="isOperate"></i>
                <!-- <span v-else>/</span> -->
                <i v-else class="el-icon-view table-icon" @click="handleEdit(scope.row)"></i>
              </div>
              <!-- 删除 -->
              <div v-if="column.key === 'delete'">
                <i class="el-icon-delete table-icon" @click="handleDelete(scope.row)" v-if="scope.row.databaseCrfSurface !== 'SUBJECT' && isOperate"></i>
                <i class="el-icon-delete table-icon" @click="handleDelete(scope.row)" v-else-if="scope.row.databaseCrfSurface === 'SUBJECT' && !disabledDeleteField.includes(scope.row.variable) && isOperate"></i>
                <span v-else>/</span>
              </div>
              <!-- 排序 -->
              <div v-if="column.key === 'sort1'">
                <i class="el-icon-sort table-icon" @click="handleSort(scope.row)" v-if="isOperate"></i>
                <span v-else>/</span>
              </div>
              <div v-if="column.key === 'variableType1'">
                <span>{{variableTypeEnumeration[scope.row.variableType]}}</span>
              </div>
              <!-- 状态 -->
              <div v-if="column.key === 'operation'" @click="handleChangeStatus(scope.row)">
                <el-switch v-if="scope.row.operation === '1'" :value ="false" active-color="#13ce66"></el-switch>
                <el-switch v-else-if="scope.row.operation === '0'" :value ="true" active-color="#13ce66"></el-switch>
              </div>
              <span v-else>{{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <add-record 
        :dialogVisible="dialogVisible" 
        :dialogTitle="dialogTitle" 
        :editData="editData"
        @handleCancel="handleCancel"
        :searchParams="searchParams"
        :referenceTableList="referenceTableList"
        :isOperate="isOperate"
        :variableConfigList="variableConfigList">
      </add-record>
      <sortData :sortVisible="sortVisible" :sortData="sortData" :sortList="sortList" @handleSortCancel="handleSortCancel"></sortData>
    </div>
  </div>
</template>
<script>

import { mapActions } from 'vuex'
import { tableColumns } from './data'
import addRecord from './component/add-variable.vue'
import sortData from './component/sort.vue'
import { cloneDeep } from 'lodash-es'
import { variableTypeEnumeration } from '@/utils/enums/ecrf-design.js'

export default {
  name: 'variable-config',
  components: {
    addRecord,
    sortData
  },

  data() {
    return {
      dialogVisible: false,
      dialogTitle: '',
      editData: {},
      variableConfigList: [],
      tableColumns,
      referenceTableList: [],
      sortVisible: false,
      sortData: {},
      sortList: [],
      queryParams: {},
      variableTypeEnumeration,
      searchParams: {},
      disabledDeleteField: ['SITENAME', 'STATUS', 'CRFSTS', 'COUNTRY', 'CRFVER', 'INVID', 'SUBJID', 'USUBJID', 'SITEID', 'INVNAM', 'STUDYID'],
      isOperate: true
    }
  },
  mounted() {
    this.queryParams = this.$route.query
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
      surface: this.queryParams.surface
    }

    if (databaseInfo.isLock === '1') {
      this.isOperate = false
    }

    this.getVariableList()
  },

  methods: {
    ...mapActions('eCRFDesign', ['qryVariableConfigList', 'deleteVariableConfig', 'updateVariableConfigStatus']),

    // 查询变量配置列表
    getVariableList() {
      const params = {
        ...this.searchParams
      }
      this.qryVariableConfigList({ params }).then((res) => {
        const { data, code } = res
        if (code === 200) {
          this.variableConfigList = data
        }
      })
    },

    // 返回上一级目录
    handleGoBack() {
      this.$router.go(-1)
    },

    // 刷新列表
    handleRefresh() {
      this.getVariableList()
    },

    // 新增变量配置
    handleAdd() {
      this.dialogVisible = true
      this.editData = {
        sort: this.variableConfigList[this.variableConfigList.length - 1].sort + 1
      }
      this.dialogTitle = '新建'
    },

    // 打开排序弹框
    handleSort(record) {
      this.sortVisible = true
      this.sortData = record
      this.sortList = cloneDeep(this.variableConfigList)

    },

    // 关闭
    handleSortCancel(type) {
      this.sortVisible = false
      if (type === 'refresh') { // 是刷新列表
        this.getVariableList()
      }
    },

    // 编辑
    handleEdit(record) {
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.editData = { 
        ...record,
        codeName: record.variableTypeValue.codeName,
        codeArrangement: record.variableTypeValue.codeArrangement,
        codeNumber: record.variableTypeValue.number,
        configure: { ...record.variableTypeValue }
      }
    },

    // 关闭弹框
    handleCancel(type) {
      this.dialogVisible = false
      if (type === 'refresh') { // 是刷新列表
        this.getVariableList()
      }
    },

    // 删除
    handleDelete(row) {
      const params = {
        id: row.id
      }
      this.$confirm('确定删除该条数据吗？', '删除提示', {
        type: 'warning'
      }).then(res => {
        this.deleteVariableConfig({ params })
          .then(res => {
            if (res.code === 200) {
              this.$message({ message: '删除成功', type: 'success' })
              this.getVariableList()
            }
          })
      })
    },

    // 状态变更
    handleChangeStatus(record) {
      if (!this.isOperate) {
        this.$message.error('数据库版本锁定中，无法操作')
        return false
      }
      const data = {
        id: record.id,
        operation: record.operation === '0' ? '1' : '0'
      }
      this.updateVariableConfigStatus({ data }).then((res) => {
        const { code } = res
        if (code === 200) {
          this.$message.success('操作成功！')
          this.getVariableList()
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
